//
//  DPSingleTon.m
//  DrinkingPlan
//
//  Created by 张德广 on 2019/3/15.
//  Copyright © 2019 Drinking Plan. All rights reserved.
//

#import "DPSingleTon.h"

@implementation DPSingleTon

+ (instancetype)shareInstance {
    static DPSingleTon *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [[[self class]alloc]init];
    });
    return instance;
}

+ (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

+ (NSString *)getCurrentDetailTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

+ (NSString *)getCurrentHour {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

+ (NSString *)weekdayStringFromDate:(NSDate *)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"Sunday", @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/SuZhou"];
    [calendar setTimeZone:timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
}

+ (int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return -1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return 1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
}

/*
 调整行间距
 */
+ (void)adjustLineSpacingOfLabel:(UILabel *)label to:(CGFloat)lineSpacing {
    NSString *textStr = label.text;
    if (textStr.length <= 0) {
        return;
    }
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:textStr];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpacing];
    [paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [textStr length])];
    label.attributedText = attributedString;
    [label sizeToFit];
}

+ (CGSize)sizeOfMultiLineLabel:(NSString *)aLabelTextString font:(UIFont *)aLabelFont constrainedToSize:(CGSize)maxSize lineSpacing:(CGFloat)lineSpacing {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
        //version < 7.0
        return [aLabelTextString sizeWithFont:aLabelFont
                            constrainedToSize:maxSize
                                lineBreakMode:NSLineBreakByTruncatingTail];
    }
    else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        //version >= 7.0
        //Return the calculated size of the Label
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:lineSpacing];
        [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
        
        return [aLabelTextString boundingRectWithSize:maxSize
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{NSFontAttributeName:aLabelFont, NSParagraphStyleAttributeName:paragraphStyle}
                                              context:nil].size;
    }
    return CGSizeZero;
}

/** 保存数据的路径 */
+ (NSString *)createFullPathForDocument:(NSString *)path {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
    
    return fullPath;
}

/** 从路径中获取保存model数组 */
+ (NSMutableArray *)readModelArrayForDocument:(NSString *)path {
    
    NSMutableArray *createCodeArray = [[NSMutableArray alloc] init];
    NSString *fullPath = [self createFullPathForDocument:path];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath])//判断dirPath路径文件夹是否已存在，此处dirPath为需要新建的文件夹的绝对路径
    {
        //根据路径读出可变data
        NSData *data = [NSData dataWithContentsOfFile:fullPath];
        //根据mutableData创建反序列化器
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        //反序列化器解码
        createCodeArray = [unarchiver decodeObjectForKey:@"model"];
        //反序列化器结束解码
        [unarchiver finishDecoding];
        
    }else {
        [[NSFileManager defaultManager] createFileAtPath:fullPath contents:nil attributes:nil];
    }
    
    return createCodeArray;
}

/** 保存数据到沙盒 */
+ (void)saveModelDictionaryInDocument:(NSMutableArray *)array andPath:(NSString *)path {
    
    // ***********归档，序列化****************
    // 1、创建一个可变的二进制流
    NSMutableData *data = [[NSMutableData alloc] init];
    // 2、创建一个归档对象（有将自定义类转化为二进制流的功能）
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    // 3、用该归档对象，把自定义类的对象，转为二进制流
    [archiver encodeObject:array forKey:@"model"];
    // 4、归档完毕
    [archiver finishEncoding];
    
    //将数据写入文件
    NSString *fullPath = [self createFullPathForDocument:path];
    [data writeToFile:fullPath atomically:YES];
}

+ (BOOL)isBlankDictionary:(NSDictionary *)dict {
    if (dict!=nil && ![dict isKindOfClass:[NSNull class]] && [dict count]!=0) {
        return NO;
    } else {
        return YES;
    }
}

+ (NSDate *)dateFromString:(NSString *)string withFormat:(NSString *)format {
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:format];
    NSDate *date = [inputFormatter dateFromString:string];
    return date;
}

+ (NSString *)stringWithFormat:(NSString *)format withDate:(NSDate *)date {
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:format];
    NSString *timestamp_str = [outputFormatter stringFromDate:date];
    return timestamp_str;
}

@end
